#    Copyright 2008, 2009 Tri-County Electric Cooperative, St. Matthews, South Carolina
#    This file is part of COOPGIS.
#    COOPGIS is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#    COOPGIS is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#    You should have received a copy of the GNU General Public License
#    along with COOPGIS.  If not, see <http://www.gnu.org/licenses/>.

#************************BEGIN Add Include Files to Path************************
import sys
NeededPaths=['/opt/coopgis/djangoproject/include', '/opt/coopgis/djangoproject']
for path in NeededPaths:
    if(not path in sys.path):
        sys.path.append(path)
#************************END   Add Include Files to Path************************
import COOPGIS_Ajax, COOPGIS_GPS, COOPGIS_Misc, COOPGIS_FormMisc, COOPGIS_ReportLab, COOPGIS_String, COOPGIS_Update, COOPGIS_FormStaker
import COOPGIS_FormManagementConsole, COOPGIS_FormCommandTracker
import os, csv, shutil, datetime, time, reportlab, djangoproject.settings, random
from django.contrib.gis.db import models
from django.contrib.gis.geos import *
from django.http import HttpResponse
from django.contrib import admin
from django.template import Context, loader
import djangoproject.settings
import _mysql as mysql
from models import *
from django import forms

def MainMenu(request):
    """MainMenu is the main screen for performaing a variety of administrative tasks"""
    ApplicationName=djangoproject.settings.COOPGISManagementConsoleApplicationName
    UserNameOrIPAddress=COOPGIS_Misc.GetUserNameOrIPAddress(request, GetDefaultMap=False, ApplicationName=ApplicationName)
    LoginStatus, applicationPermission=COOPGIS_Misc.CheckLoginPermissions(request, ApplicationName)
    form=COOPGIS_FormMisc.BuildForm(request, ApplicationName)
    if(not applicationPermission):
        t = loader.get_template('/opt/coopgis/djangoproject/templates/managementconsolemainmenu.html')
        c = Context({'LoginStatus':LoginStatus})
        return HttpResponse(t.render(c))
    Results=COOPGIS_FormManagementConsole.ProcessManagementConsoleForm(form, request, ApplicationName)
    NumberOfUnprocessedCommands=Command.objects.filter(CommandProcessedIndicator=False).count()
    t = loader.get_template('/opt/coopgis/djangoproject/templates/managementconsolemainmenu.html')
    c = Context({'LoginStatus': LoginStatus, 'Results': Results, 'NumberOfUnprocessedCommands':NumberOfUnprocessedCommands,
                 'form': form})
    return HttpResponse(t.render(c))

def CreateBackup(request):
    """Create Backup Creates a Backup of COOPGIS, puts it on the Server Desktop, and returns the ManagementConsole Main Menu Page"""
    ApplicationName=djangoproject.settings.COOPGISManagementConsoleApplicationName
    UserNameOrIPAddress=COOPGIS_Misc.GetUserNameOrIPAddress(request, GetDefaultMap=False, ApplicationName=ApplicationName)
    LoginStatus, applicationPermission=COOPGIS_Misc.CheckLoginPermissions(request, ApplicationName)
    #FIXME Disabling check for permissions for now to get daily backups working, add a check for permissions or running from localhost on server
    #if(not applicationPermission):
    #    t = loader.get_template('/opt/coopgis/djangoproject/templates/managementconsolemainmenu.html')
    #    c = Context({'LoginStatus':LoginStatus})
    #    return HttpResponse(t.render(c))
    #Create the Backup here
    os.system("sudo -u apachescript sudo rmdir -R " + djangoproject.settings.COOPGISBackupLocation) 
    os.system("sudo -u apachescript sudo mkdir " + djangoproject.settings.COOPGISBackupLocation) 
    os.system("sudo -u apachescript sudo chmod -R 777 " + djangoproject.settings.COOPGISBackupLocation) 

    BackupName='COOPGISBackup_' #+ str(datetime.datetime.today())[:10].replace('-','_')
    BackupFolderName=djangoproject.settings.COOPGISBackupLocation + BackupName + '/'
    os.system("sudo -u apachescript sudo mkdir " + BackupFolderName)
    os.system("sudo -u apachescript sudo chmod -R 777 " + BackupFolderName) 
    os.system("sudo -u apachescript sudo pg_dump coopgis > " + BackupFolderName + "coopgis.sql")
    os.system("sudo -u apachescript sudo pg_dump tcecmisc > " + BackupFolderName + "tcecmisc.sql")
    #os.system("sudo -u apachescript sudo pg_dump redmine > " + BackupFolderName + "redmine.sql")
    os.system("sudo -u apachescript sudo pg_dump inventory > " + BackupFolderName + "inventory.sql")
    os.system("sudo -u apachescript sudo cp -R /opt/coopgis " + BackupFolderName)
    os.system("sudo -u apachescript sudo cp -R /etc/apache2 " + BackupFolderName)
    os.system("sudo -u apachescript sudo cp -R /etc/postgresql " + BackupFolderName)
    os.system("sudo -u apachescript sudo cp -R /opt/cis " + BackupFolderName)
    os.system("sudo -u apachescript sudo cp -R /opt/amr " + BackupFolderName)
    os.system("sudo -u apachescript sudo cp -R /opt/inventory " + BackupFolderName)
    os.system("sudo -u apachescript sudo cp -R /opt/oms " + BackupFolderName)
    #os.system("sudo -u apachescript sudo cp -R /opt/redmine " + BackupFolderName)  #Redmine has been removed from this server
    os.system("sudo -u apachescript sudo cp -R /opt/tcecmisc " + BackupFolderName)

    os.system("sudo -u apachescript sudo chmod -R 777 " + BackupFolderName) 
    os.system("sudo -u apachescript sudo tar cvzf " + djangoproject.settings.COOPGISBackupLocation + BackupName + '.tgz ' + BackupFolderName)
    os.system("sudo -u apachescript sudo chmod -R 777 " + djangoproject.settings.COOPGISBackupLocation + BackupName + '.tgz ')
    os.system("sudo -u apachescript sudo rm -R " + BackupFolderName)
    #End Backup Creation
    t = loader.get_template('/opt/coopgis/djangoproject/templates/managementconsolemainmenu.html')
    c = Context({'LoginStatus': LoginStatus})
    return HttpResponse(t.render(c))

def CommandTracker(request):
    """Provide basic tracking functionality to figure out who ran what commands when in a given area"""
    ApplicationName=djangoproject.settings.COOPGISManagementConsoleApplicationName
    UserNameOrIPAddress=COOPGIS_Misc.GetUserNameOrIPAddress(request, GetDefaultMap=False, ApplicationName=ApplicationName)
    LoginStatus, applicationPermission=COOPGIS_Misc.CheckLoginPermissions(request, ApplicationName)
    form=COOPGIS_FormMisc.BuildForm(request, ApplicationName + 'CommandTracker')
    if(not applicationPermission):
        t = loader.get_template('/opt/coopgis/djangoproject/templates/managementconsolecommandtracker.html')
        c = Context({'LoginStatus':LoginStatus})
        return HttpResponse(t.render(c))
    Results=COOPGIS_FormCommandTracker.ProcessCommandTrackerForm(form)
    t = loader.get_template('/opt/coopgis/djangoproject/templates/managementconsolecommandtracker.html')
    c = Context({'LoginStatus':LoginStatus, 'form': form, 'Results': Results})
    return HttpResponse(t.render(c))

















 
